package com.horsen.service.user.controller.web;


import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.horsen.common.util.JwtInfo;
import com.horsen.common.util.JwtUtils;
import com.horsen.common.util.R;
import com.horsen.service.user.controller.BaseController;
import com.horsen.service.user.model.VO.OrderInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 订单 控制器
 *
 * @author Horsen
 */
@Api(tags = "订单管理")
@ApiSupport(order = 2)
@Slf4j
@RestController("WebOrder")
@RequestMapping("/web/user/orders/auth")
public class OrderController extends BaseController {

    @ApiOperationSupport(order = 1)
    @ApiOperation("根据课程ID新增一个订单")
    @PostMapping("/{courseId}")
    public R insert(@PathVariable String courseId, HttpServletRequest request) {
        JwtInfo memberInfo = JwtUtils.getMemberByJwtToken(request);
        String orderId = orderService.insert(courseId, memberInfo.getId());
        // 删除Redis缓存
        redisTemplate.delete("adminQueryAllOrders");
        return R.ok("新增订单成功").setData("orderId", orderId);
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation("根据ID获取一个订单")
    @GetMapping("/{orderId}")
    public R queryById(@PathVariable String orderId, HttpServletRequest request) {
        JwtInfo memberInfo = JwtUtils.getMemberByJwtToken(request);
        OrderInfoVO orderInfoVO = orderService.getById(orderId, memberInfo.getId());
        return orderInfoVO != null ?
                R.ok("获取ID=" + orderId + "的订单成功").setData("item", orderInfoVO)
                : R.error("获取ID=" + orderId + "的订单成功");
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation("获取订单支付状态")
    @GetMapping("/paid/{courseId}")
    public R isPaid(@PathVariable String courseId, HttpServletRequest request) {
        JwtInfo memberInfo = JwtUtils.getMemberByJwtToken(request);
        Boolean paid = orderService.isPaid(courseId, memberInfo.getId());
        return R.ok().setData("isBuy", paid);
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation("修改订单支付状态")
    @PutMapping("/{orderNo}")
    public R update(@PathVariable String orderNo, HttpServletRequest request) {
        JwtInfo memberInfo = JwtUtils.getMemberByJwtToken(request);
        // 删除Redis缓存
        redisTemplate.delete("adminQueryAllOrders");
        return orderService.pay(orderNo) ?
                R.ok("支付成功") : R.error("支付失败");
    }

}

